//
//  UseViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/25.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "UserViewController.h"
#import "UserTableViewCell.h"
#import "constantDefinition.h"
#import "AppDelegate.h"
#import "UserConfig.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "UIImageView+WebCache.h"
#import "LoginViewController.h"
#import "SliderViewController.h"

@interface UserViewController ()<UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate,UIGestureRecognizerDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)CBCharacteristic *writeCharacteristic;
@property(nonatomic,strong)CBPeripheral *myPeripheral;

@property (weak, nonatomic) IBOutlet UIImageView *powerImage;
//背景图片
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
//断开连接标签
@property (weak,nonatomic) IBOutlet UILabel * labelNoLink;
@property (copy,nonatomic) NSString *currentJudgeCharge;
@property (copy,nonatomic) NSString *judgeChargeValue;
@property (copy,nonatomic) NSString *disConnect;
@property (copy,nonatomic) NSString *judgeValue;

@end

@implementation UserViewController
{
    //300s请求电量定时器
    NSTimer *powerTimerr;
    UIAlertView *alert;
    NSMutableDictionary *userInfoDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    userInfoDic = [[NSMutableDictionary alloc] init];
    
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    [_userHeadImage.layer setMasksToBounds:YES];
    [_userHeadImage.layer setCornerRadius:45.0f];
//    [self getUserInfo];//获取用户信息 这边是多余的，在viewWillLoad已经请求过一次了，为什么还要请求一次
    
    self.writeCharacteristic = delegate.writeCharacteristic;
    self.myPeripheral = delegate.peripheral;
    //判断断开连接
    self.powerImage.image = [UIImage imageNamed:@"power6"];
    
    //显示电量写入（每300S写入一次电脑。）
    powerTimerr = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(currentPower) userInfo:nil repeats:YES];
    MBPROGRESS_ALLOC;//提示
//    self.mbProgressHud
    
    //注册通知 更新电量图标
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePowerInfo:) name:@"power" object:nil];
    //注册通知  用户信息更新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfo) name:@"notificationUpdataUserInfo" object:nil];
}

#pragma mark -
#pragma mark 更新电量图标  通知
- (void) updatePowerInfo:(NSNotification *)Not
{
    NSDictionary *dict=[Not userInfo];

    self.powerImage.image = [UIImage imageNamed:dict[@"power1"]];
    if (dict[@"keyPower1"] != nil)
    {
        _judgeValue = dict[@"keyPower1"];
    }
    else if (dict[@"keyPower2"] != nil)
    {
        _judgeValue = dict[@"keyPower2"];
    }
    else if (dict[@"keyPower3"] != nil)
    {
        _judgeValue = dict[@"keyPower3"];
    }
    else if (dict[@"keyPower4"] != nil)
    {
         _judgeValue = dict[@"keyPower4"];
    }
    else if (dict[@"keyPower5"] != nil)
    {
        _judgeValue = dict[@"keyPower5"];
    }
    _currentJudgeCharge = dict[@"keyCharge"];
    _judgeChargeValue = dict[@"keyComplete"];
    _disConnect = dict[@"disConnect"];
    
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if (delegate.Bluetooth ==YES)
    {//如果连接状态
        if ([_currentJudgeCharge isEqualToString:@"6"])
        {//充电
            self.labelNoLink.hidden = YES;//隐藏断开连接标签
            NSArray *myImages = [NSArray arrayWithObjects:
                                 [UIImage imageNamed:@"power1"],
                                 [UIImage imageNamed:@"power2"],
                                 [UIImage imageNamed:@"power3"],
                                 [UIImage imageNamed:@"power4"],
                                 [UIImage imageNamed:@"power5"],nil];
            self.powerImage.animationImages = myImages;
            self.powerImage.animationDuration = 2;
            self.powerImage.animationRepeatCount = 0;
            [self.powerImage startAnimating];
        }
        else if([_judgeChargeValue isEqualToString:@"7"])
        {//充电状态7 充电完成
            self.labelNoLink.hidden = YES;//隐藏断开连接标签
            AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
            if (delegate.judgeMonitor != YES) {
                if (delegate.Bluetooth == YES) {
                    Byte ACkValue[4] = {0};
                    ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x24; ACkValue[3] = 0xAA;
                    NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
                    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                        [delegate.peripheral writeValue:data
                                      forCharacteristic:delegate.writeCharacteristic
                                                   type:CBCharacteristicWriteWithResponse];
                    }
                    TJJLog(@"电量写入");
                    [self performSelector:@selector(writeGetCoolTime) withObject:nil afterDelay:3];
                }
            }
            [self.powerImage stopAnimating];
        }
        else
        {//具体电量
            switch ([_judgeValue intValue])
            {
                case 1:
                {
                    self.labelNoLink.hidden = YES;//隐藏断开连接标签
                    [self.powerImage stopAnimating];
                    self.powerImage.image = [UIImage imageNamed:@"power1"];
                }
                    break;
                case 2:
                {
                    
                    self.labelNoLink.hidden = YES;//隐藏断开连接标签
                    [self.powerImage stopAnimating];
                    self.powerImage.image = [UIImage imageNamed:@"power2"];
                }
                    break;
                case 3:
                {
                    self.labelNoLink.hidden = YES;//隐藏断开连接标签
                    [self.powerImage stopAnimating];
                    self.powerImage.image = [UIImage imageNamed:@"power3"];
                }
                    break;
                case 4:
                {
                    self.labelNoLink.hidden = YES;//隐藏断开连接标签
                    [self.powerImage stopAnimating];
                    self.powerImage.image = [UIImage imageNamed:@"power4"];
                }
                    break;
                case 5:
                {
                    self.labelNoLink.hidden = YES;//隐藏断开连接标签
                    [self.powerImage stopAnimating];
                    self.powerImage.image = [UIImage imageNamed:@"power5"];
                }
                    break;
                default:
                    break;
            }
        }
        
    }
    else
    {//断开连接
        [self.powerImage stopAnimating];
        self.powerImage.image = [UIImage imageNamed:@"power6"];
        self.labelNoLink.hidden = NO;//显示“断开连接”标签
    }
    
    if ([_disConnect isEqualToString:@"NO"])
    {//断开连接
        [self.powerImage stopAnimating];
        self.powerImage.image = [UIImage imageNamed:@"power6"];
        self.labelNoLink.hidden = NO;//显示“断开连接”标签
    }
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark 更新显示用户信息
- (void)updateUserInfo
{
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    if ([userConfig getCurrentNickName].length >1)
    {//设置昵称
        _userNameLabel.text = [userConfig getCurrentNickName];
    }
    else
    {
        _userNameLabel.text = @"暂无昵称";
    }
    if ([[userConfig getCurrentLevel] intValue] > 0)
    {//设置等级
        _levelLabel.text = [NSString stringWithFormat:@"Lv%@",[userConfig getCurrentLevel]];
    }
    else
    {
        _levelLabel.text = [NSString stringWithFormat:@"Lv%@",[userConfig getCurrentLevel]];
    }
    //TODO:设置头像
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    }else if (section == 1) {
        return 5;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 30;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    headView.backgroundColor = [UIColor clearColor];
    return headView;
}

#pragma mark -
#pragma mark cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 52.0;
}

#pragma mark -
#pragma mark UITableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentify = @"userCell";

    UserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"userCell" owner:nil options:nil] lastObject];
    }
    if (indexPath.section == 0)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                cell.topLine.hidden = NO;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user-newJiance"]];
                cell.cellTitleLabel.text = @"实时检测";
                cell.lineView.hidden = NO;
            }
                break;
            case 1:
            {
                cell.topLine.hidden = YES;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user-newGaishan"]];
                cell.cellTitleLabel.text = @"睡眠改善";
                cell.lineView.hidden = NO;
            }
                break;
            case 2:
            {
                cell.topLine.hidden = YES;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user-newDream"]];
                cell.cellTitleLabel.text = @"梦境控制";
                cell.lineView.hidden = NO;
            }
                break;
            case 3:
            {
                cell.topLine.hidden = YES;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user-newAuto"]];
                cell.cellTitleLabel.text = @"自然唤醒";
                cell.lineView.hidden = NO;
            }
                break;
            default:
                break;
        }
    }
    else if (indexPath.section == 1)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                cell.topLine.hidden = NO;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user - friend"]];
                cell.cellTitleLabel.text = @"我的好友";
                cell.lineView.hidden = NO;
            }
                break;
            case 1:
            {
                cell.topLine.hidden = YES;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user - jifen"]];
                cell.cellTitleLabel.text = @"积分与排名";
                cell.lineView.hidden = YES;
            }
                break;
            case 2:
            {
                cell.topLine.hidden = NO;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"usershangcheng"]];
                cell.cellTitleLabel.text = @"商城";
                cell.lineView.hidden = NO;
            }
                break;
            case 3:
            {
                cell.topLine.hidden = YES;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"usershequ"]];
                cell.cellTitleLabel.text = @"社区";
                cell.lineView.hidden = NO;
            }
                break;
            case 4:
            {
                cell.topLine.hidden = YES;
                [cell.cellHeadImage setImage:[UIImage imageNamed:@"user - set"]];
                cell.cellTitleLabel.text = @"系统设定";
                cell.lineView.hidden = NO;
            }
                break;
            default:
                break;
        }
    }
    return cell;
}

#pragma mark -
#pragma mark  didSelectRowAtIndexPath点击选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self performSelector:@selector(dissmissSelectCell) withObject:self afterDelay:0.1];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    
    delegate.judgeMonitor = YES;
    //脑电波数组初始化
    delegate.MonitorAry = [[NSMutableArray alloc] init];
    //SXW_调试
//    [self performSegueWithIdentifier:@"userToSelectMonitor" sender:nil];//心电选择界面
    
    if (indexPath.section == 0)
//    if (indexPath.section != 0)
    {
        //获取绑定状态
        UserConfig *config = [UserConfig sharingUserConfig];
        NSString *cool = [config getConnectCool];
        if ([cool intValue] == 1)
        {//如果绑定了设备
            switch (indexPath.row)
            {
                case 0:
                {
                    if (!delegate.Bluetooth)
                    {
                        TJJALERT_VIEW(@"眼罩未绑定或已断开连接！");
                    }
                    else
                    {
                        if (delegate.sleepModel)
                        {//如果设备处于睡眠状态
                            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:nil message:@"请关闭睡眠模式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alert1 show];
                        }
                        else
                        {//如果设备没有处于睡眠状态
                            //开始接收脑电数据
                            AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
//                            Byte ACkValue[4] = {0};
//                            ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x05; ACkValue[3] = 0xAA;//开始
//                            NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
                            NSData *data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_HEART_START];

                            if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                                [delegate.peripheral writeValue:data
                                              forCharacteristic:delegate.writeCharacteristic
                                                           type:CBCharacteristicWriteWithResponse];
                            }
                            delegate.judgeMonitor = YES;
                            //脑电波数组初始化
                            delegate.MonitorAry = [[NSMutableArray alloc] init];
                            [self performSegueWithIdentifier:@"userToSelectMonitor" sender:nil];//心电选择界面
                        }
                    }
                    
                }
                    break;
                case 1:
                    if (delegate.sleepModel) {
                        [self performSegueWithIdentifier:@"menuToSleep" sender:nil];
                    }else
                    {
                        UIAlertView *Currentalert = [[UIAlertView alloc] initWithTitle:nil message:@"请开启睡眠模式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [Currentalert show];
                    }
                    break;
                case 2:
                {//梦境控制
                    if (delegate.sleepModel)
                    {
                        [self performSegueWithIdentifier:@"menuTODreamTwo" sender:nil];//梦境控制界面
                    }else
                    {
                        UIAlertView *Currentalert = [[UIAlertView alloc] initWithTitle:nil message:@"请开启睡眠模式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [Currentalert show];
                    }
                }
                    break;
                case 3:
                    if (delegate.sleepModel) {
                        [self performSegueWithIdentifier:@"menuToAuto" sender:nil];
                    }else
                    {
                        UIAlertView *Currentalert = [[UIAlertView alloc] initWithTitle:nil message:@"请开启睡眠模式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [Currentalert show];
                    }
                    break;
                default:
                    ;
                    break;
            }

        }
        else
        {//未绑定设备
            UIAlertView *alertShow = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请进入设置界面绑定眼罩" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertShow.tag = 211;
            [alertShow show];
        }
    }
    else if (indexPath.section == 1)
    {
        switch (indexPath.row)
        {
            case 0:
            {//我的好友
                [self performSegueWithIdentifier:@"menuToFriend" sender:nil];
            }
                break;
            case 1:
            {//积分与排名
                [self performSegueWithIdentifier:@"menuToIntegral" sender:nil];
            }
                break;
            case 2:
            {//商城
                [self performSegueWithIdentifier:@"menuTomarket" sender:nil];
            }
                break;
            case 3:
            {//社区
                [self performSegueWithIdentifier:@"menuTocommunity" sender:nil];
            }
                break;
            case 4:
            {//系统设定
                [self performSegueWithIdentifier:@"menuToSetting" sender:nil];
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark -
#pragma mark dissmissSelectCell
- (void)dissmissSelectCell {
    [_menuTableView deselectRowAtIndexPath:[_menuTableView indexPathForSelectedRow] animated:YES];
}

#pragma mark -
#pragma mark 网络获取用户信息
- (void)getUserInfo {
    [_mbProgressHud show:YES];//HUD显示
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    NSDictionary *dic = @{@"Token":[userConfig getToken]};
    //地址
    [httpManager POST:GET_INFO parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *dic = [NetworkTool toNSDictionary:responseObject];
                  TJJLog(@"侧边栏--获取用户信息成功");
                  NSDictionary *resDic = [NetworkTool parseJSONStringToNSDictionary:dic[@"b"]];
                  
                  if ([dic[@"a"] intValue] == 1)
                  {
                      NSString *imageUrl ;
                      if ([resDic[@"image"] isKindOfClass:[NSNull class]])
                      {
                          imageUrl = @"";
                      }else {
                          imageUrl = resDic[@"image"];
                      }
                      [_userHeadImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PICTURE_HEAD,imageUrl]] placeholderImage:[UIImage imageNamed:@"user - head"]];
//                      TJJLog(@"%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PICTURE_HEAD,imageUrl]]);
                      if ([resDic[@"name"] isKindOfClass:[NSNull class]]) {//如果为空
                          _userNameLabel.text = @"暂无昵称";
                      }else {
                          _userNameLabel.text = resDic[@"name"];
                      }
                      
                      if ([resDic[@"totalpoints"] isKindOfClass:[NSNull class]])
                      {//根据字段 totalpoints 总分数，来求等级，用自定义行数  @"grade"等级字段，暂时无用，数据库根本就没改变
                          _levelLabel.text = @"Lv1";
                      }
                      else
                      {
//                          _levelLabel.text = [NSString stringWithFormat:@"Lv%@",resDic[@"grade"]];//设置等级 LV0-1-2等
//                          _levelLabel.text = [NSString stringWithFormat:@"Lv%d",[resDic[@"grade"] integerValue]>0?[resDic[@"grade"] intValue] : 0];//SXW__强化设置等级
                          _levelLabel.text = [TJJDefines getGrade:resDic[@"totalpoints"]];//设置等级
                          //TODO:等级设置
                          
                      }
                  }else if ([dic[@"a"] intValue] == -1) {
                      [self loginOut];//登录失效
                  }else if ([dic[@"a"] intValue] == 0) {
                      ALERT_VIEW(@"获取失败");
                  }
                  _mbProgressHud.hidden = YES;
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"信息获取失败");
                  _mbProgressHud.hidden = YES;
              }];
}

//页面即将显示
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    [self getUserInfo];//网络获取用户信息
    
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    if (delegate.isUpdateHardWare)
    {//做滑动，跳转到首页 标记从绑定界面过来的，监测到正在升级的情况
        SliderViewController * slider = [SliderViewController sharedSliderController];
        [slider closeSideBar];//关闭侧边栏
    }
    //设置背景图片
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];//获取当前时间秒数
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"homeBackGround" object:nil userInfo:nil];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
  
    
}


- (void)viewDidAppear:(BOOL)animated {
    //禁用滑动手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -
#pragma mark 电量写入
-(void)currentPower
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if (delegate.judgeMonitor != YES) {
        if (delegate.Bluetooth == YES) {
            Byte ACkValue[4] = {0};
            ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x24; ACkValue[3] = 0xAA;
            NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
            if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
                [delegate.peripheral writeValue:data
                              forCharacteristic:delegate.writeCharacteristic
                                           type:CBCharacteristicWriteWithResponse];
            }
            TJJLog(@"电量写入");
            [self performSelector:@selector(writeGetCoolTime) withObject:nil afterDelay:3];
        }
    }
}

#pragma mark -
#pragma mark 请求状态写入定时器
-(void)writeGetCoolTime
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    
    Byte ACkValue[4] = {0};
    ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x25; ACkValue[3] = 0xAA;
    NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
    if ([delegate.writeCharacteristic.UUID.UUIDString isEqual:@"FFF2"]) {
        [delegate.peripheral writeValue:data
                      forCharacteristic:delegate.writeCharacteristic
                                   type:CBCharacteristicWriteWithResponse];
    }
    TJJLog(@"User-侧边栏-状态写入");
}

#pragma mark -
#pragma mark 登录过期
- (void)loginOut
{
    if (TJJiOS8)
    {
        UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:Alertview animated:YES completion:nil];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];//需要提示信息变化

            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }];
        
        [Alertview addAction:action];
    }
    else
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
        alertView.tag = 97;
        [alertView show];
    }
}

#pragma mark -
#pragma mark alertView协议实现
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case 97:
        {//重新登录
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            [TJJ_SD_BLE_INSTRUCTIONS unBind:@"key"];//需要提示信息变化
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }
            break;
        default:
            break;
    }
}
@end
